<template>
	<u-modal :model-value="props.modelValue" title="输入验证码" confirmText="确定" showCancelButton @cancel="cancel"
		@confirm="confirm" confirm-color="#00D075">
		<template v-slot:default>
			<view class="u-p-30">
				<view class="item u-flex u-m-b-20">
					<view class="code">验证码</view>
					<u-image :src="data.src" @click="$u.throttle(changeImg, 1000)" :width="310" mode="widthFix"></u-image>
				</view>
				<view class="item u-p-l-30 u-p-r-30">
					<u-input placeholder="请输入验证码" v-model="data.code" maxlength="4"></u-input>
				</view>
			</view>
		</template>
	</u-modal>
</template>

<script setup>
	import {
		reactive,
		watch
	} from "vue";
	const props = defineProps({
		modelValue: Boolean
	})
	const emit = defineEmits(['confirm', 'cancel'])
	const data = reactive({
		code: '',
		src: '',
		secret_str: ''
	})
	watch(() => props.modelValue, (nv) => {
		if (nv) {
			changeImg()
		}
	})
	const cancel = () => {
		data.code = ''
		emit('cancel')
	}
	const confirm = () => {
		if (uni.$u.test.isEmpty(data.code)) return uni.$u.toast('请输入验证码')
		emit('confirm', {
			code: data.code,
			secret_str: data.secret_str
		})
		data.code = ''
	}
	// 更换验证码
	const changeImg = async () => {
		let res = await uni.$u.api.picture()
		data.src = res.src
		data.secret_str = res.secret_str
	}
</script>

<style lang="scss" scoped>
	.item {
		border: 2rpx solid #d2cece8c;
		height: 98rpx;
		display: flex;
		align-items: center;
	}

	:deep(.u-image) {
		height: 98rpx !important;
	}

	.code {
		flex: 1;
		background-color: #e6eaf099;
		height: 98rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		color: #666;
	}
</style>